<script setup>
import { Edit, Delete, Plus, UploadFilled } from '@element-plus/icons-vue'
import { onMounted, ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useTokenStore, useUserInfoStore } from '../../stores'
import { ElMessage, ElMessageBox } from 'element-plus'
import { QuillEditor } from '@vueup/vue-quill'
import '@vueup/vue-quill/dist/vue-quill.snow.css'
import { getAssignmentListByCourseIdService, getByIdService } from '../../api/assignment'
import { getScByStudentIdService } from '../../api/sc'

const router = useRouter()
const tokenStore = useTokenStore()
const userInfoStore = useUserInfoStore()
const userInfo = ref({ ...userInfoStore.userInfo })

const courses = ref([])
const assignments = ref([])

// 用户搜索时选中的分类id 和 发布状态
const courseId = ref('')
const state = ref('')

// 新增：分页相关变量
const currentPage = ref(1)
const pageSize = ref(10) // 每页显示条目数
const totalItems = ref(0) // 总条目数

// 修改是弹窗展示编辑原信息
const showSumbit = (id) => {
  router.push({ path: '/student/hw', query: { assId: id } })
}

// 前往评分
const evaluate = async (assignmentId) => {
  router.push({ path: '/assCorrect', query: { assId: assignmentId } })
}

// 显示课程分类和作业
const getCourse = async () => {
  try {
    const courseIdResponse = await getScByStudentIdService(userInfo.value.id)
    const courseIds = courseIdResponse.data.map(item => item.couId)
    const coursesData = []
    const assignmentData = []

    for (const couId of courseIds) {
      const courseResponse = await getByIdService(couId)
      const assignments = await getAssignmentListByCourseIdService(couId)
      coursesData.push({ ...courseResponse.data })
      if (assignments.data.length > 0) {
        assignments.data.forEach(assignment => {
          assignment.courseName = courseResponse.data.name
        })
        assignmentData.push(...assignments.data)
      }
    }

    courses.value = coursesData
    assignments.value = assignmentData
    totalItems.value = assignmentData.length
  } catch (error) {
    ElMessage.error('加载课程和作业信息失败')
  }
}

// 搜索作业
const getAssignment = () => {
  let filteredAssignments = assignments.value.filter(assignment => {
    return (!courseId.value || assignment.courseId === parseInt(courseId.value)) &&
           (!state.value || assignment.overdue === Number(state.value))
  })
  assignments.value = filteredAssignments
}

// 重设下拉框分类信息
const resetFilters = () => {
  courseId.value = ''
  state.value = ''
  getCourse() // 重置时也重新获取作业
}

// 作业时间信息格式化
const formatDate = (row, column) => {
  const date = row[column.property]
  return date ? new Date(date).toLocaleString() : null
}

// 分页变化处理
const handlePageChange = (newPage) => {
  currentPage.value = newPage
}

// 刷新时加载
onMounted(() => {
  getCourse()
})
</script>

<template>
  <el-card class="page-container">
    <!-- 卡牌标题 -->
    <template #header>
      <div class="header">
        <span>您的作业</span>
      </div>
    </template>
    
    <!-- 搜索表单 -->
    <el-form inline>
      <el-form-item label="课程分类：">
        <el-select placeholder="请选择" v-model="courseId">
          <el-option
            v-for="course in courses"
            :key="course.id"
            :label="course.name"
            :value="course.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="发布状态：">
        <el-select placeholder="请选择" v-model="state">
          <el-option label="开放" value="0"></el-option>
          <el-option label="已截止" value="1"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="getAssignment">搜索</el-button>
        <el-button @click="resetFilters">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 作业列表 -->
    <el-table :data="assignments.slice((currentPage - 1) * pageSize, currentPage * pageSize)" style="width: 100%" @row-click="isExpand">
      <el-table-column type="expand">
        <template #default="{ row }">
          <div>
            <p><strong>课程:</strong> {{ row.courseName }}</p>
            <p>作业要求: {{ row.description }}</p>
            <p><strong>作业前往阶段</strong></p>
            <p>截止时间: {{ row.dueDate }}</p>
            <p><strong>作业互评阶段</strong></p>
            <p>开始时间: {{ row.dueDate }}</p>
            <p>截止时间: {{ row.dueDate }}</p>
            <p class="warning-text">{{ row.reviewNote }}</p>
            <p><strong>成绩公布阶段</strong></p>
            <p>公布时间: {{ row.dueDate }}</p>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="作业标题" prop="title">
        <template #default="{ row }">
          <h1>{{ row.title }}</h1>
        </template>
      </el-table-column>
      <el-table-column label="截止时间" prop="dueDate" :formatter="formatDate"></el-table-column>
      <el-table-column label="状态">
        <template #default="{ row }">
          {{ row.isScore === 1 ? '提交阶段' : row.isScore === 2 ? '互评阶段' : '公布成绩' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="250">
        <template #default="{ row }">
          <el-button plain v-if="row.overdue === 0" type="success" @click.stop="showSumbit(row.id)">前往作业</el-button>
          <el-button plain v-else-if="row.overdue === 1" type="danger" @click.stop="showSumbit(row.id)">前往作业</el-button>
          <el-button plain v-if="row.isScore === 2" type="primary" @click.stop="evaluate(row.id)">参与互评</el-button>
          <el-button plain v-if="row.isScore === 3" type="primary" @click.stop="showScore(row.id)">查看成绩</el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="教师还没有上传作业哦~" />
      </template>
    </el-table>

    <!-- 分页组件 -->
    <el-pagination
      layout="prev, pager, next"
      :total="totalItems"
      :page-size="pageSize"
      :current-page="currentPage"
      @current-change="handlePageChange"
      style="margin-top: 20px;"
    />
  </el-card>
</template>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
.avatar-uploader {
  :deep() {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>